


from PIL import Image
import requests
from io import BytesIO


def load_image_from_url(url):
    # 发送 HTTP 请求获取图像数据
    response = requests.get(url)
    response.raise_for_status()  # 检查请求是否成功

    # 将图像数据转换为字节流
    image_data = BytesIO(response.content)

    # 使用 Pillow 打开图像
    image = Image.open(image_data)
    return image
def merge_avatar_into_qrcode(qrcode_path, avatar_path, output_path, avatar_size=80):
    # 打开二维码和头像
    qrcode = load_image_from_url(qrcode_path)
    avatar = load_image_from_url(avatar_path)

    # 调整头像大小
    avatar = avatar.resize((avatar_size, avatar_size))

    # 确保头像是 RGBA 模式，以便处理透明度
    if avatar.mode != 'RGBA':
        avatar = avatar.convert('RGBA')

    # 计算头像在二维码中的位置
    qrcode_width, qrcode_height = qrcode.size
    position = ((qrcode_width - avatar_size) // 2, (qrcode_height - avatar_size) // 2)

    # 创建一个新的透明层，用于放置头像
    overlay = Image.new('RGBA', qrcode.size, (0, 0, 0, 0))
    overlay.paste(avatar, position, avatar)

    # 将透明层叠加到二维码上
    qrcode = qrcode.convert('RGBA')
    qrcode_with_avatar = Image.alpha_composite(qrcode, overlay)

    # 保存合并后的图像
    qrcode_with_avatar.save(output_path, format='PNG')

# 使用示例
qrcode_url = "https://wework.qpic.cn/wwpic3az/381976_bTmTSlP3SP-l2Hc_1732711457/0"
avatar_url = "https://fbbc.cdn.bcebos.com/20240723/8baf69ad140c4b438dae4dda8dc2fd80.jpg"
output_path = 'D:/output.png'

merge_avatar_into_qrcode(qrcode_url, avatar_url, output_path)

